// src/context/AuthContext.tsx
import React, { createContext, useState, ReactNode, useEffect } from 'react';

interface User {
  username: string;
}

interface AuthContextType {
  isInit: boolean;
  user: User | null;
  login: (userData: User) => void;
  logout: () => void;
}

export const AuthContext = createContext<AuthContextType | undefined>(undefined);

const STORAGE_KEY = 'auth_user';

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [isInit, setIsInit] = useState(false);
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    const storedUser = localStorage.getItem(STORAGE_KEY);
    setUser(storedUser ? JSON.parse(storedUser) : null);
    setIsInit(true);
  }, []);

  const login = (userData: User) => {
    setUser(userData);
    // 将用户信息存储到 localStorage
    localStorage.setItem(STORAGE_KEY, JSON.stringify(userData));
  };

  const logout = () => {
    setUser(null);
    // 清除 localStorage 中的用户信息
    localStorage.removeItem(STORAGE_KEY);
  };

  return (
    <AuthContext.Provider value={{ isInit, user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};
